package ar.com.personalTravellers.spring;

import com.angel.base.helpers.CollectionHelper;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 *
 * @author William
 */
public class ApplicationContextSpring {
    private static ApplicationContextSpring INSTANCE;

    private static String[] contexts = new String[]
        {
            "applicationContext-model.xml",
            "applicationContext-dao.xml",
            "applicationContext-flex.xml",
            "applicationContext-services.xml",
            "applicationContext-sgflex.xml",
            "applicationContext-sgservices.xml",
            "applicationContext-sgdao.xml",
            "applicationContext-sgmodel.xml"                
        };

    private ApplicationContext applicationContext;

    private ApplicationContextSpring(String[] applicationContexts){
        super();
        if(applicationContext == null){
            int quantityContexts = CollectionHelper.sumSize(contexts, applicationContexts);
            String[] allContexts = new String[quantityContexts];
            this.addContexts(allContexts, applicationContexts, 0);
            //this.addContexts(allContexts, contexts);
            applicationContext = new ClassPathXmlApplicationContext(contexts);
        }

    }

    private String[] addContexts(String[] allContexts, String[] contextsToAdd, int fromIndex){
        int size = CollectionHelper.getSizeFromArray(contextsToAdd);
        int j = 0;
        for( int i = fromIndex; i < size ; i++){
            allContexts[i] = contextsToAdd[j];
            j++;
        }
        return allContexts;
    }

    private ApplicationContextSpring(){
        super();
        if(applicationContext == null){
            applicationContext = new ClassPathXmlApplicationContext(contexts);
        }
    }

    public synchronized static ApplicationContextSpring createInstance(String[] applicationContext){
        if(INSTANCE == null){
            INSTANCE = new ApplicationContextSpring(applicationContext);
        }
        return INSTANCE;
    }

    public synchronized static ApplicationContextSpring createInstance(){
        if(INSTANCE == null){
            INSTANCE = new ApplicationContextSpring();
        }
        return INSTANCE;
    }

    public ApplicationContext prepareApplicationContext(){
        return applicationContext;
    }

    /**
        classpath:applicationContext-sgflex.xml,
        classpath:applicationContext-sgservices.xml,
        classpath:applicationContext-sgdao.xml,
        classpath:applicationContext-sgmodel.xml
     */
}

